<template>
  <div class="components-image-cropper">
    <div class="inline-block cropper-res-img" @click="dialogVisible = true">
      <img :src="url || defaultCoverImage" alt="">
      <p class="cropper-res-img-title">更换主图</p>
    </div>
    <v-dialog
      v-model="dialogVisible"
      width="400px"
    >
      <v-card>
        <v-card-title class="text-h5 grey lighten-2">
          图片裁剪
        </v-card-title>
        <v-card-text>
          <vue-cropper
            ref="cropper"
            :img="option.img"
            :output-type="option.outputType"
            :auto-crop="option.autoCrop"
            :full="option.full"
            :auto-crop-width="option.autoCropWidth"
            :auto-crop-height="option.autoCropHeight"
            :fixed-box="option.fixedBox"
            :center-box="option.centerBox"
            :info="option.info"
          />
        </v-card-text>
        <v-card-actions>
          <v-btn @click="dialogVisible = false">取 消</v-btn>
          <v-btn color="primary" @click="updateImage">确 定</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
</template>

<script>
import { VueCropper } from 'vue-cropper'

export default {
  components: {
    VueCropper
  },
  props: {
    url: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      loading: false,
      dialogVisible: false,
      defaultCoverImage: require('./pagecover-image.png'),
      option: {
        img: '',
        outputSize: 1, // 剪切后的图片质量（0.1-1）
        full: false, // 输出原图比例截图 props名full
        autoCrop: true,
        outputType: 'png',
        // 只有自动截图开启 宽度高度才生效
        autoCropWidth: 120,
        autoCropHeight: 120,
        fixedBox: false,
        centerBox: false,
        info: false
      }
    }
  },
  methods: {
    updateImage() {
      this.loading = true
      this.$refs.cropper.getCropBlob((data) => {
        const file = blobToFile(data)
        const params = new FormData()
        params.append('file', file)
        this.$API.uploadCommonImage(params).then(res => {
          this.loading = false
          this.dialogVisible = false
          this.$emit('update:url', res.body.url)
        }).catch(() => {
          this.loading = false
        })
      })
    },
    /**
			 * 添加图片文件
			 * @param file
			 * @returns {boolean}
			 */
    beforeUpload(file) {
      if (file.size > 4 * 1024 * 1024) {
        this.$message.error('上传图片不能超过4M！')
        return
      }
      var reader = new FileReader()
      const _this = this
      reader.onload = (e) => {
        let data
        if (typeof e.target.result === 'object') {
          // 把Array Buffer转化为blob 如果是base64不需要
          data = window.URL.createObjectURL(new Blob([e.target.result]))
        } else {
          data = e.target.result
        }
        _this.option.img = data
      }
      // 转化为base64
      reader.readAsDataURL(file)
      this.dialogVisible = true
      // 转化为blob
      // reader.readAsArrayBuffer(file);
      return false
    }
  }
}
function blobToFile(blob, fileName) {
  blob.lastModifiedDate = new Date()
  blob.name = fileName || new Date().getTime()
  return blob
}
</script>

<style lang="scss" scoped>
  .cropper-res-img {
    width: 100px;
    height: 100px;
    border: 1px dashed #2196F3;
    border-radius: 3px;
    margin-bottom: 18px;
    text-align: center;
    cursor: pointer;
    transition: all 0.28s;
    position: relative;
    background: #eee 50%/contain no-repeat;
    justify-content: center;
    align-items: center;
    display: flex;
    &:hover {
      color: #2196F3;
    }
    .cropper-res-img-title {
      position: absolute;
      left: 50%;
      top: 50%;
      width: 80px;
      transform: translateY(-50%);
      transform: translateX(-50%);
      text-align: center;
      background: rgba(0, 0, 0, 0.7);
      padding: 6px 8px;
      border-radius: 4px;
      color: #eee;
      transition: all 0.28s;
      &:hover {
        background: rgba(0, 0, 0, 0.8);
        color: white;
      }
    }
    img {
      display: inline-block;
      max-width: 100%;
      max-height: 100%;
    }
  }
</style>
